"""
跑腿代办视图
处理跑腿员、订单等相关的API请求
"""

import logging
from rest_framework import status, generics, permissions, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db.models import Count, Q
from django.shortcuts import get_object_or_404
from django.db import transaction
import uuid
from django.utils import timezone

# 创建logger
logger = logging.getLogger(__name__)

from .models import ErrandRunner, ErrandOrder
from .serializers import (
    ErrandRunnerListSerializer, ErrandRunnerDetailSerializer, 
    ErrandOrderListSerializer, ErrandOrderDetailSerializer
)
from utils.response import success_response, error_response, paginated_response


class ErrandRunnerListView(generics.ListAPIView):
    """
    跑腿员列表视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ErrandRunnerListSerializer
    queryset = ErrandRunner.objects.filter(status='active', is_verified=True)
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['user__username', 'service_areas', 'service_types']
    ordering_fields = ['rating', 'total_orders', 'created_at']
    ordering = ['-rating']

    def list(self, request, *args, **kwargs):
        """获取跑腿员列表"""
        queryset = self.get_queryset()

        # 服务类型筛选
        service_type = self.request.query_params.get('service_type')
        if service_type:
            queryset = queryset.filter(service_types__contains=[service_type])

        # 服务区域筛选
        service_area = self.request.query_params.get('service_area')
        if service_area:
            queryset = queryset.filter(service_areas__contains=[service_area])

        serializer = self.get_serializer(queryset, many=True)
        return success_response(
            data=serializer.data,
            message="获取跑腿员列表成功"
        )


class ErrandRunnerDetailView(generics.RetrieveAPIView):
    """
    跑腿员详情视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ErrandRunnerDetailSerializer
    queryset = ErrandRunner.objects.filter(status='active', is_verified=True)

    def retrieve(self, request, *args, **kwargs):
        """获取跑腿员详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="获取跑腿员详情成功"
        )


class ErrandOrderCreateView(generics.CreateAPIView):
    """
    跑腿订单创建视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderDetailSerializer

    def create(self, request, *args, **kwargs):
        """创建跑腿订单"""
        # 生成订单号
        order_number = f"ERR{uuid.uuid4().hex[:10].upper()}"

        # 检查当前用户
        logger.info(f"当前请求用户: {request.user}, ID: {request.user.id}")
        logger.info(f"用户是否认证: {request.user.is_authenticated}")

        # 创建订单数据
        order_data = request.data.copy()
        order_data['order_number'] = order_number
        order_data['customer'] = request.user.id
        order_data['status'] = 'pending'

        logger.info(f"订单数据: {order_data}")
        serializer = self.get_serializer(data=order_data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    order = serializer.save()
                    return success_response(
                        data=ErrandOrderDetailSerializer(order).data,
                        message="创建订单成功"
                    )
            except Exception as e:
                return error_response(
                    message=f"创建订单失败: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            # 移除data参数，只传递message和status_code
            return error_response(
                message=f"创建订单失败: {serializer.errors}",
                status_code=status.HTTP_400_BAD_REQUEST
            )


class ErrandOrderListView(generics.ListAPIView):
    """
    跑腿订单列表视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderListSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['created_at', 'status']
    ordering = ['-created_at']

    def get_queryset(self):
        """获取订单列表"""
        user = self.request.user
        # 客户查看自己的订单
        if self.request.query_params.get('role') == 'customer':
            return ErrandOrder.objects.filter(customer=user)
        # 跑腿员查看自己的订单
        elif self.request.query_params.get('role') == 'runner':
            runner = get_object_or_404(ErrandRunner, user=user)
            return ErrandOrder.objects.filter(runner=runner)
        # 默认返回客户订单
        return ErrandOrder.objects.filter(customer=user)

    def list(self, request, *args, **kwargs):
        """获取订单列表"""
        queryset = self.get_queryset()

        # 状态筛选
        status = self.request.query_params.get('status')
        if status:
            queryset = queryset.filter(status=status)

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        start = (page - 1) * page_size
        end = start + page_size

        total_count = queryset.count()
        orders = queryset[start:end]

        serializer = self.get_serializer(orders, many=True)
        return paginated_response(
            data=serializer.data,
            count=total_count,
            page=page,
            page_size=page_size
        )


class ErrandOrderDetailView(generics.RetrieveAPIView):
    """
    跑腿订单详情视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderDetailSerializer

    def get_queryset(self):
        """获取订单详情"""
        user = self.request.user
        # 客户只能查看自己的订单
        # 跑腿员只能查看自己接的订单
        return ErrandOrder.objects.filter(
            Q(customer=user) | Q(runner__user=user)
        )

    def retrieve(self, request, *args, **kwargs):
        """获取订单详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="获取订单详情成功"
        )


class ErrandOrderAcceptView(generics.UpdateAPIView):
    """
    跑腿订单接单视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderDetailSerializer
    queryset = ErrandOrder.objects.filter(status='pending')

    def update(self, request, *args, **kwargs):
        """接单"""
        partial = kwargs.pop('partial', True)
        instance = self.get_object()

        # 检查订单是否仍然待接单
        if instance.status != 'pending':
            return error_response(
                message="订单状态已变更，无法接单",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 检查是否是跑腿员
        try:
            runner = ErrandRunner.objects.get(user=request.user, status='active')
        except ErrandRunner.DoesNotExist:
            return error_response(
                message="您不是活跃的跑腿员，无法接单",
                status_code=status.HTTP_403_FORBIDDEN
            )

        # 检查跑腿员当前正在进行的订单数量
        active_orders_count = ErrandOrder.objects.filter(
            runner=runner,
            status__in=['accepted', 'processing']
        ).count()

        if active_orders_count >= 5:
            return error_response(
                message="您当前接单数量已达上限，请完成现有订单后再接单",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 更新订单状态和跑腿员
        instance.status = 'accepted'
        instance.runner = runner
        instance.save()

        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="接单成功"
        )


class ErrandOrderCancelView(generics.UpdateAPIView):
    """
    跑腿订单取消视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderDetailSerializer

    def get_queryset(self):
        """获取可取消的订单"""
        user = self.request.user
        # 只能取消自己创建的且处于待接单状态的订单
        return ErrandOrder.objects.filter(
            customer=user,
            status='pending'
        )

    def update(self, request, *args, **kwargs):
        """取消订单"""
        partial = kwargs.pop('partial', True)
        instance = self.get_object()

        # 更新订单状态
        instance.status = 'cancelled'
        instance.updated_at = timezone.now()
        instance.save()

        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="订单已取消"
        )


class ErrandOrderCompleteView(generics.UpdateAPIView):
    """
    跑腿订单完成视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ErrandOrderDetailSerializer

    def get_queryset(self):
        """获取可完成的订单"""
        user = self.request.user
        # 只能完成自己接的且处于接单状态的订单
        return ErrandOrder.objects.filter(
            runner__user=user,
            status__in=['accepted', 'processing']
        )

    def update(self, request, *args, **kwargs):
        """完成订单"""
        partial = kwargs.pop('partial', True)
        instance = self.get_object()

        # 更新订单状态
        instance.status = 'completed'
        instance.completed_at = timezone.now()
        instance.updated_at = timezone.now()
        instance.save()

        # 更新跑腿员的订单统计
        if instance.runner:
            instance.runner.total_orders += 1
            instance.runner.completed_orders += 1
            # 简单的评分更新逻辑，这里可以根据实际需求调整
            if request.data.get('rating'):
                instance.runner.rating = (
                    instance.runner.rating * (instance.runner.completed_orders - 1) + 
                    int(request.data.get('rating'))
                ) / instance.runner.completed_orders
            instance.runner.save()

        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="订单已完成"
        )
